'''
Created on 18.11.2011

@author: smoe
'''
import xmlrpclib, sys, os
from pprint import pprint

class Server(object):
    '''
    abstraktion der XML-RPC Verbindung zum Trac-Server
    '''
    tickets = []
    notify = True

    def __init__(self, servername, path="", user=None, password=None, secure=True):
        '''
        Constructor
        '''
        schema  = "https://" if secure else "http://"
        
        if user is not None:
            auth_credentials = (user if not password else "%s:%s" % (user, password)) + "@"
            path = path + "/login"

        else:
            auth_credentials = ""
        
        self.url = schema + auth_credentials + servername + path + "/xmlrpc"
        
    def connect(self):
        self.serverproxy = xmlrpclib.ServerProxy(self.url);
                
    def fetchOpenTickets(self):
        ticket_id_list = self.serverproxy.query()
        
        self.tickets = [Ticket(self.serverproxy.ticket.get(ticket_id), self) for ticket_id in ticket_id_list]
    
    def createTicket(self, ticket):
        '''
        erstellt ein Ticket in Trac
        '''
        
        ticket.id = self.serverproxy.create(ticket.summary, ticket.description, ticket.getAttributes(), self.notify)
        
    def updateTicket(self, ticket, comment):
        '''
        aktualisiert ein Ticket in Trac
        '''

        return Ticket(self.serverproxy.update(ticket.id, comment, ticket.getAttributes(), self.notify), self)
        
_tracServer=Server()

class Ticket:
    '''
    präpariert Ticketinformationen anhand der übergebenen Attribute
    '''
    _server = _tracServer
    
    def __init__(self, attributes, server):
        self.server = server
        
        self.gtg_attributes = attributes

        if "id" in attributes and attributes["id"] is not None:
            self.trac_attributes = self.server.ticket.get(attributes["id"])
            
        
        self.setStatus()
    
    def setStatus(self):
        if self.gtg_attibutes
        
    def getAttributes(self):
        pass
        
    def saveTicket(self):
        pass
    
        
if __name__ == "__main__" :
    trac_server = Server(servername="trac.metaccount.de", user=os.environ["USER"], password=os.environ["PASSWORD"])
    pprint(trac_server.search.getSearchFilters())